#include "apue.h"
#include<syslog.h>
#include<fcntl.h>
#include<sys/resource.h>

//extern void pr_ids(char *);

void daemonize(const char *cmd)
{
    //pr_ids("into daemonize");

	int i, fd0, fd1, fd2;
	pid_t pid;
	struct rlimit rl;
	struct sigaction sa;

	/* clear file creating mask */
	umask(0);

	/* get maximum number of file description */
	if(getrlimit(RLIMIT_NOFILE, &rl) < 0)
		err_quit("%s: can't get file limit", cmd);

    /* become a session leader to lose controlling TTYs */
	if((pid = fork()) < 0)
		err_quit("%s: can't fork", cmd);
	else if(pid != 0) //parent
		exit(0);
    //sleep(1);	
	//pr_ids("after first fork in child");
	setsid();  //just in child process

	/* ensure future opens won't allocate controlling TTYs */
	sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	if(sigaction(SIGHUP, &sa, NULL) < 0)
		err_quit("%s: can't ignore SIGHUP", cmd);
	if((pid = fork()) < 0)
		err_quit("%s: can't fork", cmd);
	else if(pid != 0) //parent
		exit(0);

	/* change the current working directory */
	if(chdir("/") < 0)
		err_quit("%s: can't change directory to /", cmd);

	/* close all open file descriptors */
	if(rl.rlim_max == RLIM_INFINITY)
		rl.rlim_max = 1024;
	for(i=0; i<rl.rlim_max; i++)
		close(i);

	/* attach file descriptor 0, 1, and 2 to /dev/null */
	fd0 = open("/dev/null", O_RDWR);
	fd1 = dup(0);
	fd2 = dup(0);

	/* initialize the log file */
	openlog(cmd, LOG_CONS, LOG_DAEMON);
	if(fd0 != 0 || fd1 != 1 || fd2 != 2) {
		syslog(LOG_ERR, "unexpected file descriptors %d %d %d", fd0, fd1, fd2);
		exit(1);
	}
}


